package com.lzh.shijicloudstack.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * @author luzhiheng
 * @date 2024-10-28
 */
public class FileUtil {

    public void getPdfFileStream(HttpServletResponse response, String filePath) {
        response.reset();
        // 设置响应头
        response.setContentType("application/pdf");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition,X-DI-DOWNLOAD");
        response.setHeader("Content-Disposition", "attachment; filename=final.pdf");

        // 创建文件输入流
        try (FileInputStream fis = new FileInputStream(filePath)) {
            // 获取响应的输出流
            try (OutputStream os = response.getOutputStream()) {
                long length = new File(filePath).length();
                response.setContentLength((int) length);
                // 读取文件内容并写入输出流
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
